
package dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;



public class GenericDAO<T> implements InterfaceDAO<T>{
private EntityManager em=FactoryDAO.getFactory().createEntityManager();
    @Override
    public boolean inserir(T t) {
        try {
            em.getTransaction().begin();
            em.persist(t);
            em.getTransaction().commit();
            return true;
        } catch (Exception e) {
            em.getTransaction().rollback();
            return false;
        }
    }

    @Override
    public boolean atualizar(T t) {
        try {
             em.getTransaction().begin();
        em.merge(t);
        em.getTransaction().commit();
        return true;
        } catch (Exception e) {
            em.getTransaction().rollback();
            return false;
        }
    }

    @Override
    public boolean excluir(T t) {
        try {
             em.getTransaction().begin();
        em.remove(t);
        em.getTransaction().commit();
        return true;
        } catch (Exception e) {
            em.getTransaction().rollback();
            return false;
        }
    }

    @Override
    public T obterId(Class<T> gClass, Object id) {
        if (id!=null){
            String queryCode=gClass.getSimpleName()+ ".findByid";
            Query query=em.createNamedQuery(queryCode);
            return (T) query.setParameter("id", id).getSingleResult();
        }else {
            return null;
        }
    }

    @Override
    public List<T> obterTodos(Class<T> gClass) {
        String queryCode=gClass.getSimpleName()+".findAll";
        Query query=em.createNamedQuery(queryCode);
        return (List<T>) query.getResultList();
   }
    
}
